import axios from "axios";
import { useRouter } from "vue-router";

const router = useRouter();

// 创建 Axios 实例
const createAxiosInstance = (baseURL) => {
  const instance = axios.create({
    baseURL,
    timeout: 5000,
    headers: { terminal: "h5" },
  });

  // 请求拦截器
  instance.interceptors.request.use(
    (config) => {
      // const token = localStorage.getItem("token");
      // if (token) {
      //   config.headers["h-token"] = token;
      // }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  // 响应拦截器
  instance.interceptors.response.use(
    (response) => {
      const { RTYPE, RTMSG, ET_DATA } = response.data;
      if (RTYPE === "S") {
        let res = {};
        if (typeof ET_DATA === "string") {
          console.log(JSON.parse(ET_DATA), "ET_DATA");
          res = JSON.parse(ET_DATA);
        }
        return res;
      } else {
        //查无数据
        // RTMSG && showFailToast(RTMSG);
        return {
          status: RTYPE,
          message: RTMSG || "请求失败",
        };
      }
      // 其他错误
      // return Promise.reject(new Error("Request failed"));
    },
    (error) => {
      // 网络错误
      return Promise.reject(error);
    }
  );

  return instance;
};

// 创建请求实例
const apiUrl = import.meta.env.VITE_API_ROOT;
const request = createAxiosInstance(apiUrl);

// 封装请求方法
const service = (options) => {
  const { method = "get", data, ...rest } = options;

  // 处理 GET 请求的 params
  if (method.toLowerCase() === "get") {
    rest.params = data;
  } else {
    rest.data = data;
  }

  return request({
    method,
    ...rest,
  });
};

// 支持取消请求
const createCancelToken = () => {
  const source = axios.CancelToken.source();
  return source;
};

// 导出请求方法和取消请求的工具
export { service, createCancelToken };
